import { Component, OnInit } from '@angular/core';
import { User } from '../model/user';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/debounceTime';
import { Result } from '../model/result';
import { Router } from '@angular/router';
import { UserService } from '../service/user.service';

@Component({
  selector: 'app-registe',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  public user: User = new User();
  confirmpassword = '';
  error = '';

  constructor(public http: HttpClient, public router: Router, public userService: UserService) {
  }

  ngOnInit() {
    this.user.username = 'jjs';
    this.user.password = '123456';
    this.confirmpassword = '123456';
    this.user.nickname = '贾俊松';
    this.user.email = 'jjsjjs521@163.com';
  }

  register() {
    if (this.user.password !== this.confirmpassword) {
      this.error = '密码和确认密码不一致';
      return;
    }

    this.http.get('/testUserByUsername?username=' + this.user.username)
      .debounceTime(1000).subscribe((result: Result) => {
        if (result.error) {
          this.error = '用户名已经存在';
          return;
        } else {
          // tslint:disable-next-line:no-shadowed-variable
          this.http.post('/user', this.user).subscribe((result: Result) => {
            if (result.error === '') {
              this.router.navigateByUrl('/user/login');
            } else {
              this.error = result.error;
            }
          });
        }
      });

  }

}
